// cloudfunctions/get-card/index.js
'use strict';
exports.main = async (event, context) => {
  const db = uniCloud.database()
  const userId = event.userId

  // 获取总卡片数
  const countRes = await db.collection('cards').count()
  if (countRes.total === 0) return { code: 404, message: '暂无卡片' }

  // 随机获取卡片
  const random = Math.floor(Math.random() * countRes.total)
  const cardRes = await db.collection('cards').skip(random).limit(1).get()
  if (cardRes.data.length === 0) return { code: 404, message: '卡片获取失败' }

  // 处理用户状态
  const card = cardRes.data[0]
  return {
    code: 200,
    data: {
      _id: card._id,
      imageUrl: card.imageUrl,
      description: card.description,
      title:card.title,
      detail:card.detail,
      likeCount: card.likeCount,
      collectCount: card.collectCount,
      isLiked: card.likeUsers.includes(userId),
      isCollected: card.collectUsers.includes(userId)
    }
  }
}